<?php
declare (strict_types=1);

namespace app\api\controller\v1;

use app\api\event\WXBizDataCrypt;
use app\api\helpers\v1\traits\FileUpload;
use app\api\model\v1\AdminLog;

use app\api\model\v1\Admins;
use app\api\model\v1\WxUser;
use app\api\validate\v1\LoginValidate;
use app\BaseController;
use think\exception\ValidateException;
use think\facade\Config;
use think\facade\Env;
use think\Request;

class Wechat extends BaseController
{
    use FileUpload;


    /**
     * @User: 刘海龙
     * @Date: 2021/9/30
     * @Time: 14:51
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 微信登录
     */
    public function wxLogin()
    {
        $data = $this->request->param();
        try {
            $this->validate(['mobile' => $data['mobile'], 'password' => $data['password']], LoginValidate::class);
            if (!$admin = Admins::with(['unit' => ['community']])->where('mobile', $data['mobile'])->find()) {
                return $this->response(403, '用户名不存在');
            }
            if (!password_verify($data['password'], $admin->password)) {
                return $this->response(403, '密码错误');
            }
            $token = $this->token->createToken($admin->id);
            $admin->token = $token;
            $admin->login_time = time();
            $admin->save();
            //日志
            AdminLog::record('登录', $this->request->param(), $admin->id, $admin->username);

        } catch (ValidateException $exception) {
            // 验证失败 输出错误信息
            return $this->response(403, $exception->getError());
        }
        if ($admin['unit'] === null) {
            $admin['unit'] = [
                'gather_company_title' => '未匹配到单位'
            ];
        }
        //->with(['wxMenuAuth'=>['wxMenu']])
        $admin['role'] = $admin->roles()->find(); //当前角色
        return $this->response($admin);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/30
     * @Time: 14:33
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 重新获取token
     */
    public function getToken()
    {
        $uid = $this->request->param('uid');
        $user = Admins::find($uid);
        if (is_null($user)) {
            return $this->response(500, '用户不存在');
        }
        $token = $this->token->createToken($uid);
        $user->token = $token;
        $user->login_time = time();
        $user->save();
        return $this->response($user);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/30
     * @Time: 14:34
     * @return \think\response\Json
     * 验证token
     */
    public function tokenVerify()
    {
        $token = $this->request->param('token');
        if (!$token) {
            return $this->response(500, 'token不允许为空');
        }
        $valid = $this->verifyToken($token);
        $arr = ['isValid' => $valid];
        return json($arr);
    }

    /**
     * @param $token
     * @User: 刘海龙
     * @Date: 2021/9/30
     * @Time: 14:34
     * @return bool
     * 验证token
     */
    public function verifyToken($token)
    {
        $exist = $this->token->checkTokenJWT($token);
        if ($exist['code'] === 10000) {
            return true;
        } else {
            return false;
        }
    }


    public function testLogin()
    {

        $app_id = $this->request->param('app_id');
        $secret = $this->request->param('app_secret');
        $code = $this->request->param('code');
        $encryptedData = $this->request->param('encryptedData');
        $iv = $this->request->param('iv');
        $URL = "https://api.weixin.qq.com/sns/jscode2session?appid=$app_id&secret=$secret&js_code=$code&grant_type=authorization_code";
        $apiData = file_get_contents($URL);
        $arr_data = json_decode($apiData, true);
        if (array_key_exists('session_key', $arr_data)) {
            $info = new WXBizDataCrypt($app_id, $arr_data['session_key']);
            $errCode = $info->decryptData($encryptedData, $iv, $data);
            if ($errCode === 0){
                $phone = json_decode($data,true);
                $res = WxUser::checkMobile($phone['phoneNumber']);
                if(is_null($res)){ //为空创建
                    $user_id = WxUser::saveWxUser([
                        'nickname'=>randNickName(6),
                        'mobile'=>$phone['phoneNumber'],
                    ]);
                }else{//不为空
                    $user_id = $res->id;
                }
               return $this->getWxUserInfo($user_id);
            }else{
                halt("获取失败");
            }
        } else {
            halt("获取失败1");
        }

    }



    public function getWxUserInfo($user_id){
        $res = WxUser::getWxUserById($user_id);
        if (!$res) {
            return $this->response(403, '用户不存在');
        }
        $token = $this->token->createToken($user_id);
        $res->token = $token;
        $res->login_status = 1; //登录
        $res->save();
        return $this->response($res);
    }
}
